package com.zigong.app.ui.activities;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.View;
import android.widget.LinearLayout;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.ruihang.generalibrary.db.DBUtils;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.zigong.app.R;
import com.zigong.app.base.BaseActivity;
import com.zigong.app.beans.FCollect;
import com.zigong.app.ui.adapter.MyCollectionAdapter;
import com.zigong.app.ui.util.RBaseItemDecoration;
import com.zigong.app.ui.utils.CollectionUtils;
import com.zigong.app.ui.utils.SkipUtil;
import com.zigong.app.ui.utils.TitleUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 我的收藏
 */
public class MyCollectionActivity extends BaseActivity implements View.OnClickListener, CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    @BindView(R.id.title_top_edit)
    protected CustomFontTextView mBtnClear;
    @BindView(R.id.collection_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView mRecyclerView;
    @BindView(R.id.my_collection_no)
    protected LinearLayout no_collection;
//	@ViewInject(R.id.lv_my_subscribe)
//	private LoadingView mLoadingView;

    private MyCollectionAdapter mAdapter;
    private int currentNum;
    private int size;
    private int limit_number = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        initView();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_my_collection);
        ButterKnife.bind(this);
    }

    private void initView() {
        mBtnClear.setText(getString(R.string.setting_clear));
        mBtnClear.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setLoadMoreEnabled(false);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new RBaseItemDecoration(DensityUtil.dip2px(this, 1),
                ContextCompat.getColor(this, R.color.colorItemListDivider)));
        try {
            List<FCollect> all = DBUtils.getInstance().findAll(FCollect.class);
            size = all.size();
            if (size == 0) {
                mBtnClear.setVisibility(View.GONE);
            } else {
                mBtnClear.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        refreshLayout.autoRefresh();
    }

    /**
     * 获取到数据之后，初始化你列表
     * @param fCollects
     */
    private void initInfo(List<FCollect> fCollects) {
        if (currentNum == 0) {
            if (mAdapter == null) {
                mAdapter = new MyCollectionAdapter(this, fCollects).setItemInternalClick(itemClick);
                mRecyclerView.setAdapter(mAdapter);
            } else {
                mAdapter.setData(fCollects);
            }
        } else {
            int pos = mAdapter.getItemCount();
            mAdapter.addDatas(fCollects);
            if (pos > 0) {
                mAdapter.notifyItemChanged(pos - 1);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_top_edit:
                clearData();
                break;
        }
    }

    /**
     * 清空收藏数据
     */
    private void clearData() {
        CollectionUtils.getInstance().clearCollectionList();
        if (mAdapter != null) {
            mAdapter.clean();
        }
        if (mBtnClear != null) {
            mBtnClear.setVisibility(View.GONE);
        }
        onRefresh();
    }

    OnItemInternalClick itemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            SkipUtil.skipWithNewsItem(MyCollectionActivity.this, CollectionUtils.recoveryData((FCollect) mAdapter.getItem(position)),new HashMap<String, String>());
        }
    };

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            if (currentNum + limit_number <= size) {
                getCollectionList(currentNum + limit_number);
            }
        }
    }

    @Override
    public void onRefresh() {
        currentNum = 0;
        getCollectionList(currentNum);
    }

    /**
     * 获取收藏数据（本地收藏）
     * @param number
     */
    private void getCollectionList(final int number) {
        DBUtils.getInstance().findPageListByColumnAsycn(FCollect.class,
                null, null, null, "collectionTime", number, limit_number, true, new DBUtils.DBListAsyncCallBack<FCollect>() {
                    @Override
                    public void findListInDB(List<FCollect> result) {
                        currentNum = number;
                        if (ListUtils.isListValued(result)) {
                            no_collection.setVisibility(View.GONE);
                            refreshLayout.setVisibility(View.VISIBLE);
                            refreshLayout.setLoadMoreEnabled(currentNum + limit_number < size);
                            initInfo(result);
                        } else {
                            if (currentNum == 0) {
                                no_collection.setVisibility(View.VISIBLE);
                                refreshLayout.setVisibility(View.GONE);
                            }
                            return;
                        }

                    }

                    @Override
                    public void onEnd(String msg) {
                        super.onEnd(msg);
                        if (refreshLayout.isRefreshing()) {
                            refreshLayout.refreshComplete();
                        }
                        if (refreshLayout.isLoading()) {
                            refreshLayout.loadMoreComplete();
                        }
                    }
                });
    }
}
